<template>
  <div class="exhibition-manage-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>展览管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="handleRefresh"
        >刷新</el-button>
      </div>
      
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="展览名称">
          <el-input v-model="queryParams.name" placeholder="请输入展览名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" value="NOT_STARTED"></el-option>
            <el-option label="进行中" value="IN_PROGRESS"></el-option>
            <el-option label="已结束" value="ENDED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格区域 -->
      <el-table
        :data="exhibitionList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="name" label="展览名称" align="center"></el-table-column>
        <el-table-column prop="location" label="展览地点" align="center"></el-table-column>
        <el-table-column label="展览时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.startDate | formatDate }} 至 {{ scope.row.endDate | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="开放时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.dailyStartTime | formatDate }} 至 {{ scope.row.dailyEndTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="dailyLimit" label="每日限额" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === 'IN_PROGRESS'">进行中</el-tag>
            <el-tag type="info" v-else-if="scope.row.status === 'NOT_STARTED'">未开始</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === 'ENDED'">已结束</el-tag>
            <el-tag v-else>未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" :width="300" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
            >删除</el-button>
            <el-button
              size="mini"
              type="info"
              @click="handleViewCollections(scope.row)"
              icon="el-icon-view"
            >查看藏品</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      ></el-pagination>
      
      <!-- 编辑展览对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="exhibitionForm" :rules="rules" ref="exhibitionFormRef" label-width="100px">
          <el-form-item label="展览名称" prop="name">
            <el-input v-model="exhibitionForm.name"></el-input>
          </el-form-item>
          <el-form-item label="展览地点" prop="location">
            <el-input v-model="exhibitionForm.location"></el-input>
          </el-form-item>
          <el-form-item label="展览时间" prop="dateRange">
            <el-date-picker
              v-model="exhibitionForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="开放时间" prop="timeRange">
            <el-time-picker
              is-range
              v-model="exhibitionForm.timeRange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="HH:mm:ss"
              style="width: 100%"
            ></el-time-picker>
          </el-form-item>
          <el-form-item label="每日限额" prop="dailyLimit">
            <el-input-number v-model="exhibitionForm.dailyLimit" :min="1" :max="10000"></el-input-number>
          </el-form-item>
          <el-form-item label="展览描述" prop="description">
            <el-input type="textarea" v-model="exhibitionForm.description" rows="4"></el-input>
          </el-form-item>
          <el-form-item label="展览图片" prop="image">
            <div class="avatar-uploader">
              <div class="el-upload" @click="handleImageClick">
                <img v-if="exhibitionForm.image" :src="exhibitionForm.image && exhibitionForm.image.startsWith('data:image') ? exhibitionForm.image : 'data:image/jpeg;base64,' + exhibitionForm.image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
              <input
                type="file"
                ref="fileInput"
                style="display: none"
                accept="image/*"
                @change="handleFileChange"
              >
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ExhibitionManage',
  data() {
    return {
      // 查询参数
      queryParams: {
        name: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      },
      // 展览列表
      exhibitionList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 对话框可见性
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 是否为编辑模式
      editMode: false,
      // 展览表单
      exhibitionForm: {
        id: '',
        name: '',
        location: '',
        dateRange: [],
        timeRange: [],
        startDate: '',
        endDate: '',
        dailyStartTime:'',
        dailyEndTime:'',
        dailyLimit: 100,
        description: '',
        image: ''
      },
      // 上传头信息
      uploadHeaders: {
        Authorization: localStorage.getItem('token')
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入展览名称', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请输入展览地点', trigger: 'blur' }
        ],
        dateRange: [
          { required: true, message: '请选择展览日期', trigger: 'change' }
        ],
        timeRange: [
          { required: true, message: '请选择开放时间', trigger: 'change' }
        ],
        dailyLimit: [
          { required: true, message: '请输入每日限额', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入展览描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取展览列表
    this.getExhibitionList()
  },
  filters: {
    // 日期格式化过滤器
    formatDate(time) {
      if (!time) return ''
      return time.substring(0, 10)
    }
  },
  methods: {
    // 获取展览列表
    async getExhibitionList() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get('/exhibition/list', {
          params: this.queryParams
        })
        if (res.code !== 200) {
          return this.$message.error(res.message || '获取展览列表失败')
        }
        this.exhibitionList = res.data.records
        this.total = res.data.total
      } catch (error) {
        console.error('获取展览列表失败', error)
        this.$message.error('获取展览列表失败')
      } finally {
        this.loading = false
      }
    },
    // 处理查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getExhibitionList()
    },
    // 重置查询
    resetQuery() {
      this.queryParams = {
        name: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getExhibitionList()
    },
    // 处理刷新
    handleRefresh() {
      this.getExhibitionList()
    },
    // 处理页码变化
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum
      this.getExhibitionList()
    },
    // 处理每页条数变化
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.queryParams.pageNum = 1
      this.getExhibitionList()
    },
    // 处理添加
    handleAdd() {
      this.dialogTitle = '添加展览'
      this.editMode = false
      this.exhibitionForm = {
        id: '',
        name: '',
        location: '',
        dateRange: [],
        timeRange: ['09:00:00','17:00:00'],
        startDate: '',
        endDate: '',
        dailyStartTime:'09:00:00',
        dailyEndTime:'17:00:00',
        dailyLimit: 100,
        description: '',
        image: ''
      }
      this.dialogVisible = true
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑展览'
      this.editMode = true
      this.exhibitionForm = { 
        ...row,
        timeRange: [row.dailyStartTime, row.dailyEndTime],
        dateRange: [row.startDate, row.endDate],
      }
      console.log(this.exhibitionForm)
      this.dialogVisible = true
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm(`确认删除展览 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.$http.delete(`/exhibition/${row.id}`)
          if (res.code !== 200) {
            return this.$message.error(res.message || '删除展览失败')
          }
          this.$message.success('删除展览成功')
          this.getExhibitionList()
        } catch (error) {
          console.error('删除展览失败', error)
          this.$message.error('删除展览失败')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    // 处理查看藏品
    handleViewCollections(row) {
      // 跳转到藏品管理页面，并传递展览ID
      this.$router.push(`/admin/collection?exhibitionId=${row.id}&exhibitionName=${row.name}`)
    },
    // 处理图片点击事件
    handleImageClick() {
      this.$refs.fileInput.click()
    },
    // 处理文件选择变化
    handleFileChange(e) {
      const file = e.target.files[0]
      if (!file) return
      
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }
      
      // 将文件转换为base64
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.exhibitionForm.image = reader.result
        this.$message.success('图片上传成功')
      }
      reader.onerror = () => {
        this.$message.error('图片上传失败')
      }
      
      // 清空文件输入，以便于下次选择同一文件时也能触发change事件
      this.$refs.fileInput.value = ''
    },
    // 提交表单
    submitForm() {
      this.$refs.exhibitionFormRef.validate(async valid => {
        if (!valid) return
        
        // 处理日期范围
        if (this.exhibitionForm.dateRange && this.exhibitionForm.dateRange.length === 2) {
          this.exhibitionForm.startDate = this.exhibitionForm.dateRange[0]
          this.exhibitionForm.endDate = this.exhibitionForm.dateRange[1]
        }

        if (this.exhibitionForm.timeRange && this.exhibitionForm.timeRange.length === 2) {
          this.exhibitionForm.dailyStartTime = this.exhibitionForm.timeRange[0]
          this.exhibitionForm.dailyEndTime = this.exhibitionForm.timeRange[1]
        }
        
        try {
          let res
          if (this.editMode) {
            // 编辑展览
            res = await this.$http.put('/exhibition', this.exhibitionForm)
          } else {
            // 添加展览
            res = await this.$http.post('/exhibition', this.exhibitionForm)
          }
          
          if (res.data.code !== 200) {
            return this.$message.error(res.data.message || (this.editMode ? '编辑展览失败' : '添加展览失败'))
          }
          
          this.$message.success(this.editMode ? '编辑展览成功' : '添加展览成功')
          this.dialogVisible = false
          this.getExhibitionList()
        } catch (error) {
          console.error(this.editMode ? '编辑展览失败' : '添加展览失败', error)
          this.$message.error(this.editMode ? '编辑展览失败' : '添加展览失败')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.exhibition-manage-container {
  padding: 20px;
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      
      &:hover {
        border-color: #409EFF;
      }
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>